package com.dingding.queue.queue.consumer.listener;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.facade.queue.dto.msg.MessageRequestsDTO;
import com.dingding.queue.base.sms.ISendMessageDispatcher;

/**
 * 
 * @ClassName: MessageListener 
 * @Description: 短信发送队列监听
 * @author CHEHAUNBO 
 * @date 2016年6月13日 下午5:29:52
 * 
 */
@Component("messageListener")
public class MessageListener implements com.aliyun.openservices.ons.api.MessageListener {

	private Logger log = Logger.getLogger(MessageListener.class);

	@Resource(name = "sendMessageDispatcher")
	private ISendMessageDispatcher sendMessageDispatcher;

	@Override
	public Action consume(Message message, ConsumeContext context) {
		return parseQueueData(new String(message.getBody()));
	}

	/**
	 * 
	 * 从队列中读取短信数据
	 * 
	 * @Title: parseQueueData 
	 * @param queueData 队列中读取的数据 
	 * @author CHEHAUNBO
	 * 
	 */
	public Action parseQueueData(String queueData) {

		log.info("发送短信,原生队列中的消息内容为：" + queueData);

		MessageRequestsDTO messageRequestsDTO = null;
		try {
			messageRequestsDTO = JSONUtil.parseObject(queueData, MessageRequestsDTO.class);
		} catch (Exception e) {

			return Action.CommitMessage;
		}

		// 发送短信
		boolean flag = sendMessageDispatcher.dispatcher(messageRequestsDTO);

		if (flag) {
			return Action.CommitMessage;
		} else {
			return Action.ReconsumeLater;
		}
	}

}
